package com.secxiot.provider.user.service.impl;

import com.secxiot.common.constant.ServerStatusEnum;
import com.secxiot.common.exception.BaseRuntimeException;
import com.secxiot.common.utils.ClientUnit;
import com.secxiot.common.utils.IdWorker;
import com.secxiot.provider.system.dto.AppSchedulDto;
import com.secxiot.provider.system.dto.AppSchedulRecordDto;
import com.secxiot.provider.system.entity.AppPunchCard;
import com.secxiot.provider.system.entity.AppSchedul;
import com.secxiot.provider.system.entity.AppSchedulRecord;
import com.secxiot.provider.system.vo.AppPunchCardVo;
import com.secxiot.provider.system.vo.AppSchedulRecordVo;
import com.secxiot.provider.system.vo.AppSchedulVo;
import com.secxiot.provider.task.vo.TaskStatusVo;
import com.secxiot.provider.user.dao.*;
import com.secxiot.provider.user.dto.BindDto;
import com.secxiot.provider.user.dto.DeptDto;
import com.secxiot.provider.user.entity.*;
import com.secxiot.provider.user.service.DeptService;
import com.secxiot.provider.user.service.UserService;
import com.secxiot.provider.user.vo.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.constraints.NotNull;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Log4j2
@Transactional
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    DoctorPatientRelDoDao doctorPatientRelDao;
    @Autowired
    DeptManagerDao deptManagerDao;
    @Autowired
    UserDeptDao userDeptDao;

    @Autowired
    private SOSReceiverDao sosReceiverDao;

    @Autowired
    private UserEmergencyContactDao userEmergencyContactDao;

    @Autowired
    private UserExtraDao userExtraDao;

    @Autowired
    private DeptService deptService;

    @Autowired
    IdWorker idWorker;

    @Autowired
    private UserWxDao userWxDao;

    @Autowired
    private PunchCardDao punchCardDao;

    @Autowired
    private AppSchedulDao appSchedulDao;

    @Override
    public Integer save(UserDo userDo) {

        if (userDo.getType() == null) {
            throw new BaseRuntimeException(ServerStatusEnum.TYPE_NOTFOND);
        } else {
            //有效状态
            userDo.setStatus(1);
            Date date = new Date();
            //创建时间
            userDo.setGmtCreate(date);
            //修改时间
            userDo.setGmtModified(date);
        }
        return userMapper.save(userDo);
    }

    @Override
    public Integer registry(UserDo userDo) {
        // TODO 注册信息是否安全
        if (userDo.getType() == null) {
            //职业不能为空
            throw new BaseRuntimeException(ServerStatusEnum.TYPE_NOTFOND);
        }

        if (!"0000100001".equals(userDo.getType()) && null == userDo.getHospitalId()) {
            //判断选择非患者时验证职业所属医院是否为空
            throw new BaseRuntimeException(ServerStatusEnum.TYPE_NOTHOS);
        } else {
            String username = userDo.getUsername();
            String phone = userDo.getMobile();
            String name = userDo.getName();
            UserDo byUsername = userMapper.getByUsername(username, ClientUnit.CLIENT_TYPE_APP);
            UserDo byPhone = userMapper.getByPhone(phone, ClientUnit.CLIENT_TYPE_APP, null);
            if (byUsername != null) {
                throw new BaseRuntimeException(ServerStatusEnum.USERNAME_HAVE);
            }
            if (byPhone != null) {
                throw new BaseRuntimeException(ServerStatusEnum.PHONE_HAVE);
            } else {
                userDo.setStatus(1);
                Date date = new Date();
                //创建时间
                userDo.setGmtCreate(date);
                //修改时间
                userDo.setGmtModified(date);
            }

            String promoteCode = getPromoteCode(6);
            userDo.setPromoteCode(promoteCode);
            userDo.setClientType(ClientUnit.CLIENT_TYPE_APP);
        }
        return userMapper.registry(userDo);
    }

    @Override
    public Integer update(UserDo userDo) {
        userDo.setGmtModified(new Date());
        return userMapper.update(userDo);
    }

    @Override
    public UserDo getByPhone(String mobile, String clientType) {
        return userMapper.getByPhone(mobile, clientType, null);
    }

    @Override
    public UserDo getByWxOpenid(String wxOpenid) {
        return userMapper.getByWxOpenid(wxOpenid);
    }

    @Override
    public UserDo getById(Long userId) {
        return userMapper.getById(userId);
    }

    @Override
    public List<UserDo> selectUserAll(Map<String, Object> map) {
        return userMapper.selectUserAll(map);
    }

    //扫码加人
    @Override
    public Integer bindUserRel(BindDto bindDto) {
        @NotNull Long scannerId = bindDto.getScannerId();
        @NotNull Long userId = bindDto.getUserId();
        @NotNull Long deptId = bindDto.getDeptId();

        //查询扫码者id得职业
        UserDo scanner = userMapper.getById(scannerId);
        UserDo user = userMapper.getById(userId);
        String scannerType = scanner.getType();
        String userType = user.getType();
        Date date = new Date();
        log.info("扫码scanner:{},user:{}", scannerId, userId);
        log.info("扫码scannerType:{},userType:{}", scannerType, userType);

        if (scannerType.equals("0000100001")) {
            log.info("扫码者无权限");
            throw new BaseRuntimeException(ServerStatusEnum.BIND_EllEGAL);
        } else if (userType.equals("0000100001")) {
            DoctorPatientRelDoExample example = new DoctorPatientRelDoExample();
            example.createCriteria().andPatientIdEqualTo(userId).andDoctorIdEqualTo(scannerId).andValidEqualTo(1);
            List<DoctorPatientRelDo> rels = doctorPatientRelDao.selectByExample(example);
            if (!CollectionUtils.isEmpty(rels)) {
                boolean match = rels.stream().anyMatch(r -> r.getDeptId().equals(deptId));
                if (match) {
                    throw new BaseRuntimeException(ServerStatusEnum.BIND_REL_EXITS);
                } else {
                    for (int i = 0; i < rels.size(); i++) {
                        DoctorPatientRelDo r = rels.get(i);
                        r.setDelFlag(1);
                        doctorPatientRelDao.updateByPrimaryKeySelective(r);
                    }
                    log.info("删除旧部门关系，绑定新部门关系");
                }
            }
            DoctorPatientRelDo relDo = DoctorPatientRelDo.builder().createTime(date).createUser(scannerId)
                    .delFlag(0).deptId(deptId).doctorId(scannerId).patientId(userId).id(idWorker.nextId())
                    .valid(1).build();
            doctorPatientRelDao.insertSelective(relDo);
            log.info("绑定新部门关系");
            return 1;
        } else if (Integer.parseInt(scannerType) > Integer.parseInt(userType)) {
            log.info("进入部门分配流程");
            UserDeptDoExample ex = new UserDeptDoExample();
            ex.createCriteria().andUserIdEqualTo(userId).andValidEqualTo(1);
            List<UserDeptDo> userDeptDos = userDeptDao.selectByExample(ex);
            if (!CollectionUtils.isEmpty(userDeptDos)) {
                for (int i = 0; i < userDeptDos.size(); i++) {
                    UserDeptDo userDeptDo = userDeptDos.get(i);
                    userDeptDo.setValid(0);
                    userDeptDao.updateByPrimaryKeySelective(userDeptDo);
                }
                log.info("部门分配，作废旧部门关系");
            }
            DeptDto deptDto = deptService.getDeptByDeptId(deptId);
            UserDeptDo deptDo = UserDeptDo.builder().id(idWorker.nextId()).deptId(deptId).delFlag(0).directFlag(1).valid(1)
                    .createTime(date).createUser(scannerId).userId(userId).build();
            userDeptDao.insertSelective(deptDo);
            Long parentId = deptDto.getParentId();
            while (parentId > 0) {
                deptDto = deptService.getDeptByDeptId(parentId);
                deptDo = UserDeptDo.builder().id(idWorker.nextId()).deptId(deptDto.getDeptId()).delFlag(0).directFlag(0).valid(1)
                        .createTime(date).createUser(scannerId).userId(userId).build();
                userDeptDao.insertSelective(deptDo);
                parentId = deptDto.getParentId();
            }
            return 1;
        } else {
            log.info("其他未考虑情况");
            throw new BaseRuntimeException(ServerStatusEnum.BIND_EllEGAL);
        }
    }

    /**
     * 根据用户部门用户列表
     *
     * @param userId     用户id
     * @param userType   用户类型，0000100001	患者
     * @param deptId     部门id
     * @param directFlag 直属部门标识，null是查询所有层级， 1：只查询直属用户
     * @return
     */
    @Override
    public List<UserSimpleVo> getUserSimpleList(Long userId, List<String> userType, Long deptId, Integer directFlag, String taskType) {
        List<UserSimpleVo> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(userType) && userType.contains("0000100001")) {
            List<UserSimpleVo> patients = userMapper.selectPatientsByDeptId(deptId, directFlag);
            list.addAll(patients);
            userType.remove("0000100001");
        }

        //医护
        if (userType.size() > 0) {
            list.addAll(userMapper.selectDoctorsByDeptIdAndTypes(userType, deptId, directFlag, taskType));
        }
        return list;
    }

    /**
     * 紧急联系人
     *
     * @param userId   用户id
     * @param relation 关系
     * @param name     紧急联系人姓名
     * @param mobile   手机号
     * @return
     */
    @Override
    public UserEmergencyContactVo addContact(Long userId, String relation, String name, String mobile) {
        //Boolean b = false;
        UserEmergencyContact userEmergencyContact1 = userMapper.selectUserEmergencyContact(userId);
        if (userEmergencyContact1 != null) {
            userMapper.deleteUserEmergencyContact(userId);
        }
        UserEmergencyContact userEmergencyContact = new UserEmergencyContact();
        IdWorker idWorker = new IdWorker();
        userEmergencyContact.setId(idWorker.nextId());
        userEmergencyContact.setUserId(userId);//用户id
        userEmergencyContact.setName(name);//紧急联系人
        userEmergencyContact.setRelationship(relation);//关系
        userEmergencyContact.setMobile(mobile);//紧急联系人手机号
        userEmergencyContact.setDelFlag(0);//有效状态
        userEmergencyContact.setCreateUser(userId);//创建时间
        Date date = new Date();
        userEmergencyContact.setCreateTime(date);//创建人
        int i = userMapper.addUserEmergencyContact(userEmergencyContact);
        if (i == 1) {
            UserEmergencyContactVo contactVo = new UserEmergencyContactVo();
            BeanUtils.copyProperties(userEmergencyContact, contactVo);
            return contactVo;
        }
        return null;
    }

    @Override
    public List<PatientVo> listUserParent(Long deptId) {

        List<UserSimpleVo> userSimpleVos = userMapper.selectPatientsByDeptId(deptId, 1);
        if (CollectionUtils.isEmpty(userSimpleVos)) {
            return Collections.emptyList();
        }
        List<Long> ids = userSimpleVos.stream().map(us -> us.getUserId()).collect(Collectors.toList());
        UserExtraExample example = new UserExtraExample();
        example.createCriteria().andValidEqualTo(1).andExtraNameEqualTo("beds").andUserIdIn(ids);
        List<UserExtra> extras = userExtraDao.selectByExample(example);
        List<PatientVo> patientVos = userSimpleVos.stream().map(us -> {
            Optional<UserExtra> opt = extras.stream().filter(userExtra -> userExtra.getUserId().equals(us.getUserId())).findFirst();
            return new PatientVo(us.getUserId(), us.getUsername(), us.getName(),
                    us.getUserType(), us.getHeaderImg(), opt.isPresent() ? opt.get().getExtraValue() : "", us.getMobile(), "");
        }).collect(Collectors.toList());
        return patientVos;
    }

    @Override
    public List<UserSimpleVo> listHospitalSOSDoctor(Long hospitalId, Long deptId, String taskType) {
        return sosReceiverDao.selectHospitalSOSDoctor(hospitalId, deptId, taskType);
    }

    @Override
    public UserEmergencyContactVo getContact(Long userId) {
        UserEmergencyContactExample example = new UserEmergencyContactExample();
        example.createCriteria().andUserIdEqualTo(userId).andDelFlagEqualTo(0);
        List<UserEmergencyContact> contacts = userEmergencyContactDao.selectByExample(example);
        if (!CollectionUtils.isEmpty(contacts)) {
            UserEmergencyContact contact = contacts.get(0);
            UserEmergencyContactVo contactVo = new UserEmergencyContactVo();
            BeanUtils.copyProperties(contact, contactVo);
            return contactVo;
        }
        return null;
    }

    /**
     * 用户注册 -- SOS小程序
     *
     * @param userDo 用户注册提交信息
     * @return 用户信息
     */
    @Override
    public Integer sosRegistry(UserDo userDo) {
        String oldPromoteCode = userDo.getPromoteCode();
        if ("".equals(userDo.getWxOpenid())) {
            throw new BaseRuntimeException(ServerStatusEnum.NARCOTIC_WXOPENID);
        }
        UserDo byPhone = userMapper.getByPhone(userDo.getMobile(), ClientUnit.CLIENT_TYPE_SOS, userDo.getWxOpenid());
        Date date = new Date();
        if (byPhone == null) {
            userDo.setClientType(ClientUnit.CLIENT_TYPE_SOS);
            userDo.setStatus(1);
            userDo.setGmtCreate(date);
        }

        UserWxDo userWxDos = userWxDao.getUserWxByOpenId(userDo.getWxOpenid());
        if (userWxDos == null) {
            UserWxDo userWxDo = new UserWxDo();
            userWxDo.setUserId(userDo.getUserId());
            userWxDo.setCreateTime(new Date());
            userWxDo.setWxUserid(userDo.getWxUserid());
            userWxDo.setWxOpenid(userDo.getWxOpenid());
            userWxDo.setWxHeadImg(userDo.getWxHeadImg());
            userWxDo.setWxType("sos");
            userWxDao.insertSelective(userWxDo);
        } else {
            userWxDos.setWxOpenid(userDo.getWxOpenid());
            userWxDos.setWxHeadImg(userDo.getWxHeadImg());
            userWxDao.update(userWxDos);
        }

        if (StringUtils.isNotBlank(userDo.getWxAppId())) {
            WxAppVo wxApp = userWxDao.getWxApp(userDo.getWxAppId());
            userDo.setHospitalId(wxApp.getHospitalId());
        }

        String promoteCode = getPromoteCode(6);
        userDo.setPromoteCode(promoteCode);
        int registryUserId = userMapper.registry(userDo);

        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(userDo.getUserId());
        userAccount.setType(1);
        userAccount.setPayAccount(userDo.getMobile());
        userAccount.setClientType(userDo.getClientType());
        userAccount.setHospitalId(userDo.getHospitalId());
        userAccount.setStatus(1);
        userAccount.setCreaterId(userDo.getUserId());
        userAccount.setCreateTime(date);
        userMapper.saveUserAccount(userAccount);

        if (StringUtils.isNotBlank(oldPromoteCode)) {
            UserDo promoteUserDo = userMapper.getPromoteCode(oldPromoteCode);
            if (null != promoteUserDo) {
                UserPromote userPromote = new UserPromote();
                userPromote.setPromoteCode(oldPromoteCode);
                userPromote.setUserId(promoteUserDo.getUserId());
                userPromote.setNewUserId(userDo.getUserId());
                userPromote.setStartTime(date);
                userPromote.setEndTime(date);
                userPromote.setIsUnified(0);
                userPromote.setStatus(1);
                userPromote.setCreaterId(userDo.getUserId());
                userPromote.setCreateTime(date);
                userMapper.saveUserPromote(userPromote);
                if (null != promoteUserDo.getIntegralCount() && promoteUserDo.getIntegralCount() > 0) {
                    promoteUserDo.setIntegralCount(promoteUserDo.getIntegralCount() + 10);
                } else {
                    promoteUserDo.setIntegralCount(10L);
                }
                userMapper.update(promoteUserDo);
            }
        }
        return registryUserId;
    }

    @Override
    public Integer narcoticRegistry(UserDo userDo) {
        //判断 患者 医生 药师 监管
        if ("".equals(userDo.getType())) {
            throw new BaseRuntimeException(ServerStatusEnum.NARCOTIC_DRUGS_TYPE_EMPTY);
        }

        if ("".equals(userDo.getWxOpenid())) {
            throw new BaseRuntimeException(ServerStatusEnum.NARCOTIC_WXOPENID);
        } else {
            String username = userDo.getUsername();
            String phone = userDo.getMobile();
            String name = userDo.getName();
            UserDo byPhone = userMapper.getByPhone(phone, ClientUnit.CLIENT_TYPE_YY, null);
            if (byPhone == null) {
                userDo.setStatus(1);
                Date date = new Date();
                //创建时间
                userDo.setGmtCreate(date);
                //修改时间
                userDo.setGmtModified(date);
            }

            UserWxDo userWxDos = userWxDao.getUserWxByOpenId(userDo.getWxOpenid());
            if (userWxDos == null) {
                UserWxDo userWxDo = new UserWxDo();
                userWxDo.setUserId(userDo.getUserId());
                userWxDo.setCreateTime(new Date());
                userWxDo.setWxUserid(userDo.getWxUserid());
                userWxDo.setWxOpenid(userDo.getWxOpenid());
                userWxDo.setWxHeadImg(userDo.getWxHeadImg());
                userWxDo.setWxType("narcotic");
                userWxDao.insertSelective(userWxDo);
            } else {
                userWxDos.setWxOpenid(userDo.getWxOpenid());
                userWxDao.update(userWxDos);
            }
            userDo.setClientType(ClientUnit.CLIENT_TYPE_YY);
        }
        return userMapper.registry(userDo);
    }

    /**
     * 添加考勤记录
     *
     * @param punchCard 打卡对象
     * @return
     */
    @Override
    public Integer addPunchCard(AppPunchCard punchCard) {
        return punchCardDao.insertSelective(punchCard);
    }

    /**
     * 获取考勤记录列表(30天内)
     *
     * @param userId     用户ID
     * @param hospitalId 医院ID
     * @param dateTime   打卡时间
     * @return
     */
    @Override
    public List<AppPunchCardVo> getPunchCardList(Long userId, Long hospitalId, Date dateTime) {
        return punchCardDao.getPunchCardList(userId, hospitalId, dateTime);
    }

    /**
     * 获取打卡记录
     *
     * @param userId     用户ID
     * @param hospitalId 医院ID
     * @param punchType  打卡类型
     * @param punchTime  打卡时间
     * @return
     */
    @Override
    public AppPunchCardVo getPunchCard(Long userId, Long hospitalId, String punchType, Date punchTime) {
        return punchCardDao.getPunchCard(userId, hospitalId, punchType, punchTime);
    }

    /**
     * 添加排班
     *
     * @param appSchedulDto 排班对象
     * @return
     */
    @Override
    public Integer addAppSchedul(AppSchedulDto appSchedulDto) throws ParseException {
        Date date = new Date();
        Long schedulId = idWorker.nextId();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月份是MM
        List<AppSchedulRecordDto> recordDtoList = appSchedulDto.getAppSchedulRecordDto();
        for (AppSchedulRecordDto recordDto : recordDtoList) {
            AppSchedulRecord schedulRecord = AppSchedulRecord.builder()
                    .schedulId(schedulId)
                    .hospitalId(appSchedulDto.getHospitalId())
                    .userId(recordDto.getUserId())
                    .schedulType(recordDto.getSchedulType())
                    .schedulDate(simpleDateFormat.parse(recordDto.getSchedulDate()))
                    .status(1)
                    .createUser(appSchedulDto.getUserId())
                    .createTime(date)
                    .build();
            appSchedulDao.saveSchedulRecord(schedulRecord);
        }
        AppSchedul appSchedul = AppSchedul.builder()
                .schedulId(schedulId)
                .hospitalId(appSchedulDto.getHospitalId())
                .deptId(appSchedulDto.getDeptId())
                .startTime(simpleDateFormat.parse(appSchedulDto.getStartTime()))
                .endTime(simpleDateFormat.parse(appSchedulDto.getEndTime()))
                .status(1)
                .createUser(appSchedulDto.getUserId())
                .createTime(date)
                .build();
        return appSchedulDao.insertSelective(appSchedul);
    }

    /**
     * 添加排班记录
     *
     * @param appSchedulRecord 排班记录
     * @return
     */
    @Override
    public Integer addAppSchedulRecord(AppSchedulRecord appSchedulRecord) {
        return appSchedulDao.saveSchedulRecord(appSchedulRecord);
    }

    /**
     * 获取排班记录
     *
     * @param userId     用户ID
     * @param hospitalId 医院ID
     * @return
     */
    @Override
    public List<AppSchedulVo> getAppSchedulList(Long userId, Long hospitalId) {
        List<AppSchedulVo> schedulList = appSchedulDao.getSchedulList(userId, hospitalId);
        for (AppSchedulVo schedulVo : schedulList) {
            List<AppSchedulRecordVo> recordVoList = new ArrayList<AppSchedulRecordVo>();
            List<AppSchedulRecordVo> schedulRecordVoList = appSchedulDao.getSchedulRecordVoList(null, hospitalId, schedulVo.getSchedulId());
            Map<Long, List<AppSchedulRecordVo>> recordMap = new HashMap<Long, List<AppSchedulRecordVo>>();
            for (AppSchedulRecordVo recordVo : schedulRecordVoList) {
                if (recordMap.containsKey(recordVo.getUserId())) {
                    List<AppSchedulRecordVo> appSchedulRecordVos = recordMap.get(recordVo.getUserId());
                    appSchedulRecordVos.add(recordVo);
                    recordMap.put(recordVo.getUserId(), appSchedulRecordVos);
                } else {
                    List<AppSchedulRecordVo> appSchedulRecordVos = new ArrayList<AppSchedulRecordVo>();
                    appSchedulRecordVos.add(recordVo);
                    recordMap.put(recordVo.getUserId(), appSchedulRecordVos);
                }
            }

            for (Long key : recordMap.keySet()) {
                List<String> schedulTypeList = new ArrayList<String>();
                List<AppSchedulRecordVo> appSchedulRecordVos = recordMap.get(key);
                Map<String, List<String>> typeMap = new HashMap<String, List<String>>();
                Iterator<AppSchedulRecordVo> iter = appSchedulRecordVos.iterator();
                while (iter.hasNext()) {
                    AppSchedulRecordVo schedulRecordVo = iter.next();
                    String date = DateFormatUtils.format(schedulRecordVo.getSchedulDate(), "yyyy-MM-dd");
                    if (typeMap.containsKey(date)) {
                        List<String> list = typeMap.get(date);
                        list.add(schedulRecordVo.getSchedulType());
                        typeMap.put(date, list);
                        iter.remove();
                    } else {
                        List<String> list = new ArrayList<String>();
                        list.add(schedulRecordVo.getSchedulType());
                        typeMap.put(date, list);
                    }
                }

                for (AppSchedulRecordVo recordVo : appSchedulRecordVos) {
                    String date = DateFormatUtils.format(recordVo.getSchedulDate(), "yyyy-MM-dd");
                    recordVo.setSchedulTypeMap(typeMap.get(date));
                }
            }
            schedulVo.setSchedulRecordVoMap(recordMap);
        }
        return schedulList;
    }

    /**
     * 获取排班记录
     *
     * @param userId     用户ID
     * @param hospitalId 医院ID
     * @param schedulId  排班ID
     * @return
     */
    @Override
    public List<AppSchedulRecordVo> getAppSchedulRecordList(Long userId, Long hospitalId, Long schedulId) {
        return appSchedulDao.getSchedulRecordVoList(userId, hospitalId, schedulId);
    }

    /**
     * 获取微信对象
     *
     * @param appId 微信AppID
     * @return
     */
    @Override
    public WxAppVo getWxApp(@RequestParam(value = "appId", required = true) String appId) {
        return userWxDao.getWxApp(appId);
    }

    /**
     * 获取任务接收者当前任务
     *
     * @param receiverId 接收人用户ID
     * @return
     */
    @Override
    public List<TaskStatusVo> getTaskByReceiverId(Long receiverId) {
        return userWxDao.getTaskByReceiverId(receiverId);
    }

    /**
     * 获取分享用户列表
     *
     * @param userId 用户ID
     * @return
     */
    @Override
    public List<UserVo> getPromoteUserList(Long userId, Long pageNo, Long pageSize) {
        return userMapper.getPromoteUserList(userId, pageNo * pageSize, pageSize);
    }

    /**
     * 绑定分享码
     *
     * @param userId      用户ID
     * @param promoteCode 邀请码
     * @return
     */
    @Override
    public Integer bingPromoteCode(Long userId, String promoteCode) {
        Date date = new Date();
        UserDo promoteUserDo = userMapper.getPromoteCode(promoteCode);
        if (null == promoteUserDo) {
            throw new BaseRuntimeException(ServerStatusEnum.PROMOTE_USER_NULL);
        }

        UserPromote promote = userMapper.getUserPromote(userId);
        if (null != promote) {
            throw new BaseRuntimeException(ServerStatusEnum.PROMOTE_USER_BING);
        }

        UserPromote userPromote = new UserPromote();
        userPromote.setPromoteCode(promoteCode);
        userPromote.setUserId(promoteUserDo.getUserId());
        userPromote.setNewUserId(userId);
        userPromote.setStartTime(date);
        userPromote.setEndTime(date);
        userPromote.setIsUnified(0);
        userPromote.setStatus(1);
        userPromote.setCreaterId(userId);
        userPromote.setCreateTime(date);
        int i = userMapper.saveUserPromote(userPromote);

        if (null != promoteUserDo.getIntegralCount() && promoteUserDo.getIntegralCount() > 0) {
            promoteUserDo.setIntegralCount(promoteUserDo.getIntegralCount() + 10);
        } else {
            promoteUserDo.setIntegralCount(10L);
        }
        userMapper.update(promoteUserDo);
        return i;
    }

    /**
     * 绑定用户提现账号
     *
     * @param userId     用户ID
     * @param type       账户类型
     * @param payAccount 账号
     * @return
     */
    @Override
    public Integer bingUserAccount(Long userId, Integer type, String payAccount) {
        Date date = new Date();
        UserDo userDo = userMapper.getById(userId);
        if (null == userDo) {
            throw new BaseRuntimeException(ServerStatusEnum.NOT_DATA_FOUND);
        }
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(userDo.getUserId());
        userAccount.setType(type);
        userAccount.setPayAccount(payAccount);
        userAccount.setClientType(userDo.getClientType());
        userAccount.setHospitalId(userDo.getHospitalId());
        userAccount.setStatus(1);
        userAccount.setCreaterId(userDo.getUserId());
        userAccount.setCreateTime(new Date());
        return userMapper.saveUserAccount(userAccount);
    }

    /**
     * 编辑用户提现账号
     *
     * @param userId     用户ID
     * @param type       账户类型
     * @param payAccount 账号
     * @return
     */
    @Override
    public Integer editUserAccount(Long userId, Integer type, String payAccount) {
        Date date = new Date();
        UserDo userDo = userMapper.getById(userId);
        if (null == userDo) {
            throw new BaseRuntimeException(ServerStatusEnum.NOT_DATA_FOUND);
        }
        UserAccount account = userMapper.getUserAccount(userId);
        account.setStatus(0);
        account.setModifierId(userDo.getUserId());
        account.setModifyTime(date);
        userMapper.updateUserAccount(account);

        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(userDo.getUserId());
        userAccount.setType(type);
        userAccount.setPayAccount(payAccount);
        userAccount.setClientType(userDo.getClientType());
        userAccount.setHospitalId(userDo.getHospitalId());
        userAccount.setStatus(1);
        userAccount.setCreaterId(userDo.getUserId());
        userAccount.setCreateTime(new Date());
        return userMapper.saveUserAccount(userAccount);
    }

    @Override
    public UserAccount getUserAccount(Long userId) {
        return userMapper.getUserAccount(userId);
    }

    /**
     * 获取邀请码
     *
     * @param length 邀请码长度
     * @return
     */
    private String getPromoteCode(int length) {
        StringBuilder codeVal = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            // 输出字母还是数字
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            // 字符串
            if ("char".equalsIgnoreCase(charOrNum)) {
                // int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
                codeVal.append((char) (65 + random.nextInt(26)));
            } else {
                codeVal.append(String.valueOf(random.nextInt(10)));
            }
        }
        UserDo userDo = userMapper.getPromoteCode(codeVal.toString());
        if (null != userDo) {
            return getPromoteCode(length);
        } else {
            return codeVal.toString();
        }
    }

    public void deleteLogFile(String date) {
        String[] fileList = {"task", "provider", "registry", "narcotic", "gateway", "consumer", "nohup.out"};
        for (String file : fileList) {
            String fileName = "";
            if (file.equals("nohup.out")) {
                fileName = "nohup.out";
            } else {
                fileName = "applog/" + file + "/" + file + "-" + date + ".log";
            }
            log.error("删除的文件名:" + fileName);
            File f = new File(fileName);
            if (f.exists() && f.isFile()) {
                if (f.delete()) {
                    log.error("删除文件成功" + fileName);
                } else {
                    log.error("删除文件失败" + fileName);
                }
            } else {
                log.error("删除文件失败:文件未找到-" + fileName);
            }
        }
    }
}
